<?php

namespace app\admin\controller\mall\order;

use app\common\controller\Backend;
use think\Db;

/**
 * 退单
 *
 * @icon fa fa-circle-o
 */
class Refund extends Backend
{

    /**
     * Refund模型对象
     * @var \app\common\model\mall\order\Refund
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\order\Refund;
        $this->view->assign("refundresonList", $this->model->getRefundresonList());
        $this->view->assign("refundstatusList", $this->model->getRefundstatusList());
    }

    public function index() {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->alias("c")
                ->join("__MALL_ORDER_ORDER__ o", "c.order_id=o.id", "LEFT")
                ->field("c.*,o.orderNo")
                ->where($where)
                ->count();

            $list = $this->model->alias("c")
                ->join("__MALL_ORDER_ORDER__ o", "c.order_id=o.id", "LEFT")
                ->field("c.*,o.orderNo")
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 平台处理退款
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->alias('orf')
            ->join('__MALL_ORDER_ORDER__ o','orf.order_id=o.id', "INNER")
            ->where('orf.id',$ids)
            ->field('o.id order_id,orderNo,goodsMoney,deliverMoney,useScore,scoreMoney,totalMoney,realTotalMoney,orf.backMoney,orf.*')
            ->find();
        if (!$row) $this->error(__('No Results were found'));
        if ($this->request->isPost()){
            //在线退款
            $result = $this->orderRefund($ids);
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }

    /**
     * 在线支付原路退款
     */
    public function orderRefund($ids = NULL){
        $id = $ids?$ids:(int)input('post.id');
        if($id==0) $this->error("操作失败!");
        $refund = $this->model->get($id);
        if(empty($refund) || $refund->refundStatus!=1) $this->error("该退款订单不存在或已退款!");
        $rs = array();
        $order = \app\common\model\mall\order\Order::get($refund->order_id);
        if($order->payType==1) {
            switch ($order->payFrom) {
                case "wallets":
                    $rs = $this->saveOrderRefund($refund, $order);
                    break;
                case "weixinpays":
                    //$wm = model("admin/Weixinpays");
                    //$rs = $wm->orderRefund($refund,$order);
                    break;
                case "app_weixinpays":
                    //$wm = model("admin/WeixinpaysApp");
                    //$rs = $wm->orderRefund($refund,$order);
                    break;
                case "alipays":
                    //$am = model("admin/Alipays");
                    //$rs = $am->orderRefund($refund,$order);
                    break;
                default:
                    $rs = $this->saveOrderRefund($refund, $order);
                    break;
            }
        }
        return $rs;
    }

    /**
     * 余额和其他在线支付保存退款记录
     */
    public function saveOrderRefund($refund,$order){
        $content = input('post.refundRemark');
        $lockCashMoney = $order["lockCashMoney"];
        if(!(in_array($order->status,["canceled","rejected"]) && $order->refundis==0 && ($order->payis==1 || ($order->payType==0 && $order->useScore>0)))) $this->error("无效的退款订单!");
        Db::startTrans();
        try{
            //修改订单状态,清除锁定金额
            $order->refundis = 1;
            if($order->lockCashMoney > 0) $order->lockCashMoney = 0;
            //没有修改状态，排除
            $order->status = "finished";
            $order->save();
            $shopmoneylog = $scorelog = $monlog =[];
            //创建用户资金流水记录
            $mon = ($lockCashMoney>$refund->backMoney)?$refund->backMoney:$lockCashMoney;
            if($mon>0){
                $monlog = \app\common\model\User::money($mon,$order->user_id,'订单【'.$order->orderNo.'】退款¥'.$mon."。".(($content!='')?"【退款备注】：".$content:''));
            }

            if($order->useScore>0){
                $scorelog = \app\common\model\User::score($order->useScore,$order->user_id,"返还订单【".$order->orderNo."】积分".$order->useScore."个");
            }

            //如果有钱剩下，那么就退回到商家钱包
            $shopMoneys = $order->realTotalMoney-$refund->backMoney;
            if($shopMoneys>0){
                //创建商家资金流水
                \app\common\model\mall\shop\Shop::money($shopMoneys,$order->shop_id,'订单【'.$order->orderNo.'】退款，返回商家金额¥'.$shopMoneys."。");

                //发送商家信息
            }

            //修改退款单信息
            $refundTradeNo = $order->payFrom?$order->payFrom.";":"";
            $refundTradeNo += empty($monlog)?"":"moneylog:".$monlog->id.";";
            $refundTradeNo += empty($scorelog)?"":"scorelog:".$scorelog->id.";";
            $refundTradeNo += empty($shopmoneylog)?"":"shopmoneylog:".$shopmoneylog->id;
            $refund->refundTradeNo = $refundTradeNo;
            $refund->refundRemark = $content;
            $refund->refundTime = date('Y-m-d H:i:s');
            $refund->refundStatus = 2;
            $refund->refundTo = $order->user_id;
            $refund->save();

            Db::commit();
            $this->success("退款成功!");
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 微信和支付宝在线支付保存退款记录
     */
    public function complateOrderRefund($obj){
        Db::startTrans();
        try{
            $content = $obj['refundRemark'];
            $refundTradeNo = $obj['refundTradeNo'];
            $refundId = $obj['refundId'];
            $refund = $this->get($refundId);
            $order = model('\app\common\model\mall\order\Order')->get($refund->orderId);
            if(!(in_array($order->status,["canceled","rejected"]) && $order->refundis==0 && ($order->payis==1 || ($order->payType==0 && $order->useScore>0)))) $this->error("无效的退款订单!");
            //修改退款单信息
            $refund->refundRemark = $content;
            $refund->refundTime = date('Y-m-d H:i:s');
            $refund->refundStatus = 2;
            $refund->refundTradeNo = $refundTradeNo;
            //$refund->refundTo = $$obj['user_id_text'];
            $refund->save();
            //修改订单状态
            $order->refundis = 1;
            $order->save();

            if($order->useScore>0){
                \app\common\model\User::score($order->useScore,$order->user_id,"返还订单【".$order->orderNo."】积分".$order->useScore."个");
            }
            //发送一条用户信息

            //如果有钱剩下，那么就退回到商家钱包
            $shopMoneys = $order->realTotalMoney-$refund->backMoney;
            if($shopMoneys>0){
                //创建商家资金流水
                \app\common\model\mall\shop\Shop::money($shopMoneys,$order->shop_id,'订单【'.$order->orderNo.'】退款，返回商家金额¥'.$shopMoneys."。");
                //发送商家信息
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Db::rollback();
            return false;
        }
        return false;
    }

}
